package ernie.pages;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import misc.MimeTypeMapper;

/**
 * @author Filip Lindqvist <buggfille@gmail.com>
 * @created 12:07:00 PM - Nov 25, 2011
 */
public class FilePage implements Page {

    private final String child;
    private final File root;

    public FilePage(File root, String child) {
        this.child = child;
        this.root = root;
    }

    @Override
    public String getContent() {
        StringBuilder sb = new StringBuilder();
        File f = new File(root, child);
        sb.append(child).append("<br>");
        sb.append(root.getAbsolutePath()).append("<br>");
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(f));
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException ioe) {
            sb.append(ioe.getMessage()).append("<br>")
                    .append(f.getAbsolutePath());
        }
        return sb.toString();
    }

    @Override
    public String file() {
        return child;
    }

    private String getMimeType(File f) {
        if (!f.isFile()) {
            return "unknown";
        }

        String name = f.getName();
        String ext = name.substring(name.lastIndexOf('.') + 1);

        return MimeTypeMapper.getMimeType(ext);
    }
}